<template>
  <div>
    <van-nav-bar
      left-arrow
      @click-left="onClickLeft"
      right-text="搜索"
      @click-right="onSearch"
    >
      <template #title>
        <van-search
          v-model.trim="value"
          shape="round"
          placeholder="请输入搜索关键词"
          @search="onSearch"
        >
        </van-search>
      </template>
    </van-nav-bar>
    <h2>历史记录</h2>
    <ul>
      <li
        @click="historySearch(item)"
        v-for="(item, index) in history"
        :key="index"
      >
        <a href="javascript:void(0)">{{ item }}</a>
      </li>
    </ul>
    <hr />
    <h2>搜索结果</h2>
    <ul>
      <li
        @click="newsDetailsFn(item.id)"
        v-for="(item, index) in newsList"
        :key="index"
      >
        <a
          href="javascript:void(0)"
          v-html="
            item.title.replaceAll(
              value,
              `<span style='color:red;'>${value}</span>`
            )
          "
        ></a>
      </li>
      <div v-if="flag" class="box">暂无数据，换个关键词试试呗</div>
    </ul>
    <hr />
  </div>
</template>

<script>
import { search } from "@/apis/get.js";
export default {
  data() {
    return {
      value: "",
      history: localStorage.getItem("historySeacrhList")
        ? JSON.parse(localStorage.getItem("historySeacrhList"))
        : [],
      newsList: [],
      flag: false,
    };
  },
  methods: {
    // 返回首页
    onClickLeft() {
      this.$router.push({
        path: "index",
      });
    },
    // 搜索事件
    onSearch() {
      if (!this.value) {
        this.$toast("搜索内容不能为空");
        return;
      }
      if (this.history.indexOf(this.value) == -1) {
        this.history.push(this.value);
        // 历史记录本地保存
        localStorage.setItem("historySeacrhList", JSON.stringify(this.history));
      }
      this.api(this.value);
    },
    // 历史记录搜索
    historySearch(val) {
      this.value = val;
      this.api(this.value);
    },
    // 接口函数封装
    api(val) {
      search({ keyword: val }).then((res) => {
        this.flag = false;
        // console.log(res);
        this.newsList = res.data.data;
        if (res.data.data.length == 0) {
          // console.log(78);
          this.flag = true;
        }
      });
    },

    newsDetailsFn(id) {
      this.$router.push({
        path: "newsDetails",
        query: {
          id,
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.van-search {
  width: 260px;
  border-radius: 15px;
}
a {
  color: black;
}
li {
  padding: 5px;
}
.box {
  width: 100%;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
</style>